<?php

namespace app\admin\controller;

use think\Request;
use think\Controller;
use think\facade\Db;
use app\admin\model\Accountnumber as admin;

class Accountnumber extends BaseAdmin
{
    //列表
    public function Accountnumber()
    {
        $admin = new admin();
        $res = $admin::orderRaw('IFNULL(update_time,create_time) desc')->paginate(20);

        $count = $admin::count();
        $this->assign(['count'=>$count,'res'=>$res]);
        return view('list');
    }

    //添加
    public function adduser()
    {
        if (request()->ispost()) {
            $data = [
                'username'     => !empty(input('username')) ? trim(match_chinese(input('username'))) : '',
                'password'     => !empty(input('password')) ? trim(md5(match_chinese(input('password')))) : '',
                'status'       => !empty(input('status')) ? trim(input('status')) : '',
                'create_time'  => time(),
            ];

            $admin = new admin();
            $add = $admin::insert($data);
            if ($add) {
                return json(['code' => 200, 'msg' => '添加成功']);
            } else {
                return json(['code' => 500, 'msg' => '添加失败']);
            }
        }
        return view('add');
    }

    //修改
    public function edituser()
    {
        $admin = new admin();
        if(request()->ispost()){
            $data = input('post.');
            $data['username'] = !empty(input('username')) ? trim(match_chinese(input('username'))) : '';
            $data['password'] = !empty(input('password')) ? trim(md5(match_chinese(input('password')))) : '';
            $data['update_time'] = time();
            $edit = $admin->allowField(true)->update($data);
            if($edit){
                return json(['code' => 200,'msg' => '修改成功']);
            }else{
                return json(['code' => 500,'msg' => '修改失败']);
            }
        }
        $user = $admin::find(input('id'));
        $this->assign(['user' => $user]);
        return view('edit');
    }

    //删除
    public function userdel(){
        $admin = new admin();
        $id = (int)input('post.id');
        $res = $admin::where('id',$id)->delete();
        if (!$res) {
            exit(json_encode(array('code' => 1, 'msg' => '删除失败')));
        }
        exit(json_encode(array('code' => 0, 'msg' => '删除成功')));
    }
}